//
//  StatusPictureView.swift
//  sinaOnceAgain
//
//  Created by 王相超 on 16/2/22.
//  Copyright © 2016年 chuanzhi. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage


class StatusPictureView: UICollectionView {
    
    
    //配置类型的属性
    private let pictureCellID = "pictureCellID"
    
    //配图视图的数据源数组
    var imageURLS: [NSURL]? {
        
        didSet{
            
            //计算配图视图的大小
            let pSize = calculatePictureViewSieze()
            
            //给信配图视图的大小
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(pSize)
            }
            
            //刷新视图
            reloadData()
    
            //更新测试label的文案
            textLabel.text = "\(imageURLS?.count ?? 0)"
        }
    }
    
    
    
    //实例化流水布局
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        //实例化流水布局
        let flowLayout = UICollectionViewFlowLayout()
        //设置layout
        flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth)
        //设置最小间距
        flowLayout.minimumInteritemSpacing = PictureCellMargin
        flowLayout.minimumLineSpacing = PictureCellMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        //注册cell
        self.registerClass(PictureCell.self, forCellWithReuseIdentifier: pictureCellID)
        
        //设置数据源
        self.dataSource = self
        
        self.scrollsToTop = false
        
        //设置背景颜色
        self.backgroundColor = UIColor.whiteColor()
        
        //添加测试label
        self.addSubview(textLabel)
        textLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    let itemWidth = (ScreenWidth - StatusCellMargin * 2 - 2 * PictureCellMargin) / 3
    
    //根据配图视图的数量 来计算配图视图的的真是大小
    private func calculatePictureViewSieze() -> CGSize {
        
        //获取图片的数量
        let imageCount = imageURLS?.count ?? 0
        if imageCount == 0 {
            
            return CGSizeZero
        }
        
        //获取流水布局
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        //如果是单张图片
        if imageCount == 1 {
            
            //返回和图片一样
            let imageSize = CGSize(width: 150, height: 250)
            
            //设置itenSize
            layout.itemSize = imageSize
            
            return imageSize
        }
        
        //重新设置collectView的  cell的大小
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        if imageCount == 4 {
            
            //配图视图的大小的计算
            let w = itemWidth * 2 + PictureCellMargin
            return CGSize(width: w, height: w)
        }
        
        /*
        1,2,3   -> 1
        4,5,6   -> 2
        7,8,9   -> 3
        */
        
        //计算行数
        let row = CGFloat((imageCount - 1) / 3 + 1)
        let w = itemWidth * 3 + PictureCellMargin * 2
        let h = itemWidth * row + (row - 1) * PictureCellMargin
        return CGSizeMake(w, h)
    }
    
    private lazy var textLabel: UILabel = UILabel(text: "", fontSize: 40, textColor: UIColor.redColor())

}

//数据源方法
extension StatusPictureView: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLS?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellID, forIndexPath: indexPath) as! PictureCell
        
        //设置调试颜色
        //判断奇偶
        // cell.backgroundColor = indexPath.item % 2==0 ?UIColor.redColor() :UIColor.greenColor()
        
        //赋值
        cell.imageURL = imageURLS![indexPath.item]
        
        return cell
    }
}

//自定义cell  类之间可以写在同一个控制器中
private class PictureCell: UICollectionViewCell {
  
    //外部设置的图片URL属性
    var imageURL: NSURL? {
        
        didSet{
            
            iconView.sd_setImageWithURL(imageURL)
        }
    }
    
    //重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor(white: 0.95, alpha: 1)
        setupUI()   
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置界面
    private func setupUI() {
        contentView.addSubview(iconView)
        //设置约束
        iconView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    //懒加载视图
    private lazy var iconView: UIImageView = {
       
        let iv = UIImageView()
        
        iv.contentMode = .ScaleAspectFill
        
        //裁剪
        iv.clipsToBounds = true
        
        return iv
    }()
}
